<?php
namespace pays\Gateways\alipay;
class AlipaySdk{
    protected $gatewayUrl = 'https://openapi.alipay.com/gateway.do';
    protected $appId;
    protected $charset;
    protected $returnUrl;
    protected $notifyUrl;
    protected $method;
    protected $rsaPrivateKey;
    protected $totalFee;
    protected $outTradeNo;
    protected $orderName;
    protected $getPost;
	protected $account;
	
    public function __construct()
    {
        $this->charset = 'UTF-8';
    }
    public function setAppid($appid)
    {
        $this->appId = $appid;
    }
    public function setMethod($method)
    {
        $this->method = $method;
    }
    public function setReturnUrl($returnUrl)
    {
        $this->returnUrl = $returnUrl;
    }
    public function setNotifyUrl($notifyUrl)
    {
        $this->notifyUrl = $notifyUrl;
    }
    public function setRsaPrivateKey($rsaPrivateKey)
    {
        $this->rsaPrivateKey = $rsaPrivateKey;
    }
    public function setTotalFee($payAmount)
    {
        $this->totalFee = $payAmount;
    }
    public function setOutTradeNo($outTradeNo)
    {
        $this->outTradeNo = $outTradeNo;
    }
    public function setOrderName($orderName)
    {
        $this->orderName = $orderName;
    }
    public function setGetPost($getPost)
    {
        $this->getPost = $getPost;
    }
	public function setAccount($account)
    {
        $this->account = $account;
    }
    public function doPay()
    {
        //请求参数
        $requestConfigs = array(
            'out_trade_no'=>$this->outTradeNo,
            'total_amount'=>$this->totalFee,
            'subject'=>$this->orderName,
            'timeout_express'=>'2h'
        );
        $totalParams = array(
            //公共参数
            'app_id' => $this->appId,
            'method' => $this->method,
            'format' => 'json',
            'charset'=>$this->charset,
            'sign_type'=>'RSA2',
            'timestamp'=>date('Y-m-d H:i:s'),
            'version'=>'1.0',
            'notify_url' => $this->notifyUrl,
            'return_url' => $this->returnUrl,
            'biz_content'=>json_encode($requestConfigs),
        );
        $totalParams["sign"] = $this->generateSign($totalParams, $totalParams['sign_type']);
        
        //dump($totalParams);die;
        if($this->getPost){
            if ("GET" == strtoupper($this->getPost)) {	
                //value做urlencode
                $preString=$this->getSignContentUrlencode($totalParams);
                //dump($preString);
                //die;
                //拼接GET请求串
                $requestUrl = $this->gatewayUrl."?".$preString;
                return $requestUrl;
            } else {
                //拼接表单字符串
                return $this->buildRequestForm($totalParams);
            }
        }else{
            $result = $this->curlPost($this->gatewayUrl,$totalParams);
            $result = json_decode($result,true);
            $result = $result['alipay_trade_precreate_response'];
            return $result;
        }
    }
    public function doQuery()
    {
        //请求参数
        $requestConfigs = array(
            'out_trade_no'=>$this->outTradeNo,
        );
        $totalParams = array(
            //公共参数
            'app_id' => $this->appId,
            'method' => 'alipay.trade.query',
            'format' => 'json',
            'charset'=>$this->charset,
            'sign_type'=>'RSA2',
            'timestamp'=>date('Y-m-d H:i:s'),
            'version'=>'1.0',
            'notify_url' => $this->notifyUrl,
            'return_url' => $this->returnUrl,
            'biz_content'=>json_encode($requestConfigs),
        );
        $totalParams["sign"] = $this->generateSign($totalParams, $totalParams['sign_type']);
        $result = $this->curlPost($this->gatewayUrl,$totalParams);
        $result = mb_convert_encoding($result, 'UTF-8', 'UTF-8');
        $result = json_decode($result,true);
        return $result['alipay_trade_query_response'];
        
    }
	public function transfer(){
        //请求参数
        $requestConfigs = array(
            'out_biz_no'=>$this->outTradeNo,
            'payee_type'=>'ALIPAY_LOGONID',
            'payee_account'=>$this->account,
            'amount'=>$this->totalFee,
            'payer_show_name'=>'无人售货机-转账',
            'remark'=>'无人售货机收益'
        );
        $totalParams = array(
            //公共参数
            'app_id' => $this->appId,
            'method' => 'alipay.fund.trans.toaccount.transfer',
            'format' => 'json',
            'charset'=>$this->charset,
            'sign_type'=>'RSA2',
            'timestamp'=>date('Y-m-d H:i:s'),
            'version'=>'1.0',
            'biz_content'=>json_encode($requestConfigs),
        );
        $totalParams["sign"] = $this->generateSign($totalParams, $totalParams['sign_type']);
        $result = $this->curlPost($this->gatewayUrl,$totalParams);
        $result = mb_convert_encoding($result, 'UTF-8', 'UTF-8');
        $result = json_decode($result,true);
        return $result['alipay_fund_trans_toaccount_transfer_response'];
    }
    private function getSignContentUrlencode($params){
        //return $this->getSignContent($param);
        ksort($params);
        $stringToBeSigned = "";
        $i = 0;
        foreach ($params as $k => $v) {
            if (false === $this->checkEmpty($v) && "@" != substr($v, 0, 1)) {
                // 转换成目标字符集
                $v = $this->characet($v, $this->charset);
                if($i == 0) {
                    $stringToBeSigned .= "$k"."=".urlencode($v);
                }else{
                    $stringToBeSigned .= "&"."$k"."=".urlencode($v);
                }
                $i++;
            }
        }
        unset ($k, $v);
        return $stringToBeSigned;
    }
    private function buildRequestForm($para_temp){
        $sHtml = "<form id='alipaysubmit' name='alipaysubmit' action='https://openapi.alipay.com/gateway.do?charset=".$this->charset."' method='POST'>";
        while (list ($key, $val) = each ($para_temp)) {
            if (false === $this->checkEmpty($val)) {
                $val = str_replace("'","&apos;",$val);
                $sHtml.= "<input type='hidden' name='".$key."' value='".$val."'/>";
            }
        }
        //submit按钮控件请不要含有name属性
        $sHtml = $sHtml."<input type='submit' value='ok' style='display:none;''></form>";
        $sHtml = $sHtml."<script>document.forms['alipaysubmit'].submit();</script>";
        return $sHtml;
    }
    private function generateSign($params,$signType='RSA'){
        return $this->sign($this->getSignContent($params), $signType);
    }
    private function sign($data, $signType = "RSA") {
        $priKey=$this->rsaPrivateKey;
        $res = "-----BEGIN RSA PRIVATE KEY-----\n" .
            wordwrap($priKey, 64, "\n", true) .
            "\n-----END RSA PRIVATE KEY-----";
        ($res) or die('您使用的私钥格式错误，请检查RSA私钥配置');
        if ("RSA2" == $signType) {
            openssl_sign($data, $sign, $res, version_compare(PHP_VERSION,'5.4.0', '<') ? SHA256 : OPENSSL_ALGO_SHA256); //OPENSSL_ALGO_SHA256是php5.4.8以上版本才支持
        } else {
            openssl_sign($data, $sign, $res);
        }
        $sign = base64_encode($sign);
        return $sign;
    }
    private function checkEmpty($value) {
        if (!isset($value))
            return true;
        if ($value === null)
            return true;
        if (trim($value) === "")
            return true;
        return false;
    }
    private function getSignContent($params) {
        ksort($params);
        $stringToBeSigned = "";
        $i = 0;
        foreach ($params as $k => $v) {
            if (false === $this->checkEmpty($v) && "@" != substr($v, 0, 1)) {
                // 转换成目标字符集
                $v = $this->characet($v, $this->charset);
                if ($i == 0) {
                    $stringToBeSigned .= "$k" . "=" . "$v";
                } else {
                    $stringToBeSigned .= "&" . "$k" . "=" . "$v";
                }
                $i++;
            }
        }
        unset ($k, $v);
        return $stringToBeSigned;
    }
    private function characet($data, $targetCharset) {
        if (!empty($data)) {
            $fileType = $this->charset;
            if (strcasecmp($fileType, $targetCharset) != 0) {
                $data = mb_convert_encoding($data, $targetCharset, $fileType);
                //$data = iconv($fileType, $targetCharset.'//IGNORE', $data);
            }
        }
        return $data;
    }
    private function curlPost($url = '', $postData = '', $options = array())
    {
        if (is_array($postData)) {
            $postData = http_build_query($postData);
        }
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30); //设置cURL允许执行的最长秒数
        if (!empty($options)) {
            curl_setopt_array($ch, $options);
        }
        //https请求 不验证证书和host
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $data = curl_exec($ch);
        curl_close($ch);
        return $data;
    }
}
